package com.runvp.rest.biz;

import java.util.List;

import com.runvp.common.core.text.Convert;
import com.runvp.common.enums.DataSource;
import com.runvp.common.enums.EnableStatus;
import com.runvp.common.enums.UserType;
import com.runvp.common.exception.base.BaseException;
import com.runvp.common.hex.HexConvert;
import com.runvp.common.util.ToolUtils;
import com.runvp.common.util.auth.SecurityUtils;
import com.runvp.common.utils.ShiroUtils;
import com.runvp.common.utils.StringUtils;
import com.runvp.service.biz.service.IBizCustomerWalletService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.runvp.common.annotation.Log;
import com.runvp.common.enums.BusinessType;
import com.runvp.service.biz.domain.BizCustomer;
import com.runvp.service.biz.service.IBizCustomerService;
import com.runvp.common.core.controller.BaseController;
import com.runvp.common.core.domain.AjaxResult;
import com.runvp.common.utils.poi.ExcelUtil;
import com.runvp.common.core.page.TableDataInfo;

/**
 * 消费者Controller
 *
 * @author runvp
 * @date 2022-09-15
 */
@Controller
@RequestMapping("/biz/customer")
public class BizCustomerController extends BaseController {
    private String prefix = "biz/customer";

    @Autowired
    private IBizCustomerService bizCustomerService;
    @Autowired
    private IBizCustomerWalletService bizCustomerWalletService;

    @RequiresPermissions("biz:customer:view")
    @GetMapping()
    public String customer(ModelMap mmap) {
        return prefix + "/customer";
    }

    @RequiresPermissions("biz:customer:view")
    @GetMapping("/cloudCard")
    public String cloudCard(ModelMap mmap) {
        return prefix + "/cloudCard";
    }
    @RequiresPermissions("biz:customer:view")
    @GetMapping("/channel")
    public String channel(ModelMap mmap) {
        return prefix + "/channel";
    }
    /**
     * 查询消费者列表
     */
    @RequiresPermissions("biz:customer:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(BizCustomer bizCustomer) {
        startPage();
        List<BizCustomer> list = bizCustomerService.selectBizCustomerList(bizCustomer);
        return getDataTable(list);
    }

    /**
     * 导出消费者列表
     */
    @RequiresPermissions("biz:customer:export")
    @Log(title = "消费者", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(BizCustomer bizCustomer) {
        List<BizCustomer> list = bizCustomerService.selectBizCustomerList(bizCustomer);
        ExcelUtil<BizCustomer> util = new ExcelUtil<BizCustomer>(BizCustomer.class);
        return util.exportExcel(list, "消费者数据");
    }

    /**
     * 新增消费者
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存消费者
     */
    @RequiresPermissions("biz:customer:add")
    @Log(title = "消费者", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(BizCustomer bizCustomer) {
        if(StringUtils.isNotEmpty(bizCustomer.getPassword())){
            bizCustomer.setPassword(SecurityUtils.encryptPassword(bizCustomer.getPassword()));
        }
        return toAjax(bizCustomerService.insertBizCustomer(bizCustomer));
    }
    /**
     * 创建云卡
     */
    @RequiresPermissions("biz:customer:add")
    @Log(title = "创建云卡", businessType = BusinessType.INSERT)
    @PostMapping("/create/cloudCard")
    @ResponseBody
    public synchronized AjaxResult createCloudCard(BizCustomer bizCustomer) {
        bizCustomer.setOpenId(HexConvert.hexNumber2Ten(bizCustomer.getOpenId()));
        checkRepeat(bizCustomer.getOpenId());
        bizCustomer.setType(UserType.CLOUD_CARD.getCode());
        bizCustomer.setSource(DataSource.CLOUD_CARD_CENTER.getCode());
        bizCustomer.setCreateBy(ShiroUtils.getLoginName());
        bizCustomer.setPid(0L);
        bizCustomer.setStatus(EnableStatus.ENABLE.getCode());
        int r = bizCustomerService.insertBizCustomer(bizCustomer);
        bizCustomerWalletService.customerWallet(bizCustomer.getId());
        return toAjax(r);
    }

    /**
     * 校验卡号是否存在
     * @param cardNo
     */
    private void checkRepeat(String cardNo){
        BizCustomer query = new BizCustomer();
        query.setOpenId(cardNo);
        List<BizCustomer> customers = bizCustomerService.selectBizCustomerList(query);
        if(!CollectionUtils.isEmpty(customers)){
            throw new BaseException("卡号【"+cardNo+"】已存在");
        }
    }
    /**
     * 修改消费者
     */
    @RequiresPermissions("biz:customer:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        BizCustomer bizCustomer = bizCustomerService.selectBizCustomerById(id);
        mmap.put("bizCustomer", bizCustomer);
        return prefix + "/edit";
    }
    /**
     * 修改消费者
     */
    @RequiresPermissions("biz:customer:edit")
    @GetMapping("/editChannel/{id}")
    public String editChannel(@PathVariable("id") Long id, ModelMap mmap) {
        BizCustomer bizCustomer = bizCustomerService.selectBizCustomerById(id);
        mmap.put("bizCustomer", bizCustomer);
        return prefix + "/editChannel";
    }
    /**
     * 修改消费者
     */
    @RequiresPermissions("biz:customer:edit")
    @GetMapping("/editCloudCard/{id}")
    public String editCloudCard(@PathVariable("id") Long id, ModelMap mmap) {
        BizCustomer bizCustomer = bizCustomerService.selectBizCustomerById(id);
        mmap.put("bizCustomer", bizCustomer);
        return prefix + "/editCloudCard";
    }
    /**
     * 修改保存消费者
     */
    @RequiresPermissions("biz:customer:edit")
    @Log(title = "消费者", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(BizCustomer bizCustomer) {
        if(StringUtils.isNotEmpty(bizCustomer.getPassword())){
            bizCustomer.setPassword(SecurityUtils.encryptPassword(bizCustomer.getPassword()));
        }
        return toAjax(bizCustomerService.updateBizCustomer(bizCustomer));
    }

    /**
     * 删除消费者
     */
    @Transactional(rollbackFor = Exception.class)
    @RequiresPermissions("biz:customer:remove")
    @Log(title = "消费者", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        String[] arr = Convert.toStrArray(ids);
        Long lid;
        for(String id:arr){
            lid = ToolUtils.strTOLong(id);
            bizCustomerService.deleteBizCustomerById(lid);
            bizCustomerWalletService.deleteBizCustomerWalletByCustomerId(lid);
        }
        return toAjax(1);
    }
}
